<?php
include("config.php");
session_start();
if(isset($_SESSION['tree'][$_GET['id']]))
	$this_session = $_SESSION['tree'][$_GET['id']];
else
	$this_session = array();
unset($_SESSION['tree']);
$_SESSION['tree'][$_GET['id']] = $this_session;
// if(!isset($_SESSION['user_id']))
// 	header('location:index.php');
if(!isset($_SESSION['username']))
	return 0;
error_reporting(0);
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="bg" lang="bg">
<head>
	<title><?php echo mb_convert_encoding('Вътрешна система за autohit','Windows-1251','UTF-8'); ?></title>
	<meta http-equiv="content-type" content="text/html; charset=Windows-1251" />

	<!-- Scripts -->
	<script type='text/javascript' src='js/scripts.js'></script>

	<!-- Style -->
	<link rel="stylesheet" type="text/css" href="css/styles.css" />
	<style>a{ text-decoration: none; color: black; }</style>
	<!-- Fancybox -->
	<script type="text/javascript" src="fancybox/lib/jquery-1.10.1.min.js"></script>
	<script type="text/javascript" src="fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
	<script type="text/javascript" src="fancybox/source/jquery.fancybox.js?v=2.1.5"></script>

	<link rel="stylesheet" type="text/css" href="fancybox/source/jquery.fancybox.css?v=2.1.5" media="screen" />

	<link rel="stylesheet" type="text/css" href="fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" />
	<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>

	<link rel="stylesheet" type="text/css" href="fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" />
	<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>

	<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script>
	<script type="text/javascript">
		function iframeInfoBox(id, manufacturer_id, model_id){
			$.fancybox.open({
					href : "iframe.php?id="+id+"&manufacturer_id="+manufacturer_id+"&model_id="+model_id,
					type : "iframe",
					padding : 5
				});
		}
	</script>
</head>
<body>

<?php
/**
	MANUFACTURY
*/
//default param
$level_nodes = array();
if( (isset($_GET['sub_id'])))
{
	if( strpos($_GET['sub_id'], '-') )
	{
		$sub_id_explode = explode('-', $_GET['sub_id']);
		$last_sub_id = end($sub_id_explode);
		$level_nodes['level1Node'] = $sub_id_explode[0];
		if( (isset($sub_id_explode[1])) && $sub_id_explode[1] )
			$level_nodes['level2Node'] = (int) $sub_id_explode[1];

		if( (isset($sub_id_explode[2])) && $sub_id_explode[2] )
			$level_nodes['level3Node'] = (int) $sub_id_explode[2];
	}
	else
	{
		$level_nodes['level1Node'] = $_GET['sub_id'];
		$last_sub_id = $_GET['sub_id'];
	}
}
else
	$last_sub_id = 0;

$_SESSION['flag_tree'][$_GET['id']][$last_sub_id] = !$_SESSION['flag_tree'][$_GET['id']][$last_sub_id];

$languageId = 32;
$pathinfo = pathinfo($_SERVER['PHP_SELF']);
if(isset($_GET['filterText']) && (strlen(trim($_GET['filterText'])) > 2) ){
	mb_internal_encoding('Windows-1251');
	$post = urldecode(trim($_GET['filterText']));
	$post = mb_strtolower($post);

	$_POST['filterText'] = $post;
}

if(!isset($client))
{
	$options = array(
		'languageId' => $languageId,
		'login' => 'autohit2',
		'password' => 'bont39er',
		'encoding' => 'ISO-8859-1',
		'trace' => true,
		'exceptions' => true
	);
	$client = new SoapClient('http://autohit.web-catalogue.eu/main/service/articlegroup.wsdl',$options);
}

if( isset($_POST['filterText']) && (strlen(trim($_POST['filterText'])) > 2) )
{
	mb_internal_encoding('Windows-1251');
	$post = urldecode(trim($_POST['filterText']));
	$post = mb_strtolower($post);

	$parameters_products = array_merge(array('languageId' => $languageId, 'treeType' => 1, 'filterText' => $post, 'vehicleTypeId'=>$_GET['id']),$level_nodes);
	$icon = '&filterText='.urlencode(trim($_POST['filterText']));
}
else{
	$message = "";
	if( isset($_POST['filterText']) )
		$message = mb_convert_encoding('Моля въведете минимум три символа.','Windows-1251','UTF-8');
	$icon = '';
}
$results_products = $client->getFullArticleGroupTree($parameters_products);

if(!is_array($results_products->tree))
	$results_products->tree = array($results_products->tree);
if($results_products)
{
// All fuel - select product
	foreach($_SESSION['fuel_type'] as $key => $data)
	{
		if(is_numeric($key))
			$fuel_type[$data->id] = $data->name;
		else
			$fuel_type[$_SESSION['fuel_type']->id] = $_SESSION['fuel_type']->name;
	}
	
// All vehicle - select vehicle
	foreach($_SESSION['vehicle'] as $key => $data)
	{
		if($data->id==$_GET['id']){
			if(is_numeric($key)){

				if(substr($data->manufacturedTo,0,4))
					$checkVehicleYear = substr($data->manufacturedFrom,0,4).'-'.substr($data->manufacturedTo,0,4);
				else
					$checkVehicleYear = substr($data->manufacturedFrom,0,4);

				$vehicleName = $data->name;
				$vehicleDesc =	(isset($data->engines) && isset($data->engines->description)) ? $data->engines->description : '';
				$vehicleYear = $checkVehicleYear;
				$vehicleEngine= $data->kw.' / '.$data->hp;
				$vehicleFuel = $fuel_type[$data->fuelType];
				$vehicleCCM  = $data->ccm;
				$vehicleBodyTypeName = $data->bodyTypeName;
			}
			else{
				if(substr($_SESSION['vehicle']->vehicle->manufacturedTo,0,4))
					$checkVehicleYear = substr($_SESSION['vehicle']->vehicle->manufacturedFrom,0,4).'-'.substr($_SESSION['vehicle']->vehicle->manufacturedTo,0,4);
				else
					$checkVehicleYear = substr($_SESSION['vehicle']->vehicle->manufacturedFrom,0,4);

				$vehicleName = $_SESSION['vehicle']->vehicle->name;
				$vehicleDesc =	(isset($_SESSION['vehicle']->vehicle->engines) && isset($_SESSION['vehicle']->vehicle->engines->description)) ? $_SESSION['vehicle']->vehicle->engines->description : '';
				$vehicleYear = $checkVehicleYear;
				$vehicleEngine= $_SESSION['vehicle']->vehicle->kw.' / '.$_SESSION['vehicle']->vehicle->hp;
				$vehicleFuel = $fuel_type[$result_show->vehicle->fuelType];
				$vehicleCCM  = $_SESSION['vehicle']->vehicle->ccm;
				$vehicleBodyTypeName = $_SESSION['vehicle']->vehicle->bodyTypeName;	
			}
			$_SESSION['label'] = $vehicleName.' '.$vehicleYear;
		}
	}
?>
	<div style="float: left; margin-bottom: 10px; font-size: 14px; width: 100%;">
		<div style="float:left; width: 100%; margin-bottom: 5px; font-size: 14px; font-weight: bold;">
			<img src='images/info.gif' onmouseover="this.style.cursor='pointer';" onmouseout="this.style.cursor='normal';" onClick='iframeInfoBox(<?php echo $_GET['id']; ?>, <?php echo $_GET['manufacturer_id']; ?>, <?php echo $_GET['model_id']; ?>);' alt='' style='float: left; margin-right: 10px;' />
<?php
				if( isset($_SERVER['HTTPS'] )  && $_SERVER['HTTPS'] != 'off' ) 
					$redirect_path = 'https://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
				else
					$redirect_path = 'http://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
				if(isset($_SESSION['engine_code']) && ($_SESSION['engine_code']) )
					$location = "parent.window.location.href='index.php?manufacturerId=".$_GET['manufacturer_id']."&engineId=". $_SESSION['engine_id']."&engine_code=". urlencode($_SESSION['engine_code'])."'";
				else
				{
					$location = 'ajaxManufacturerLoadModels(1,'.$_GET['manufacturer_id'].')';
					$_SESSION['engine_id'] = 0;
				}
?>
			<div id="leki_avtomobili" style="float: left; width: 123px; height: 15px;" onClick='parent.window.location.href = "<?php echo $redirect_path; ?>"' onmouseover='this.style.cursor="pointer";' onmouseout='this.style.cursor="normal";'></div>
			<div style="float: left;">&nbsp;>>&nbsp;</div>
			<div style="float: left;" class="steplink" onClick="<?php echo $location?>"><?php echo $_SESSION['manufacturers'][$_GET['manufacturer_id']]; ?></div>
			<div style="float: left;">&nbsp;>>&nbsp;</div>
			<div style="float: left;"><a class="steplink" href="ajax_soap.php?op=2&manufacturer_id=<?php echo $_GET['manufacturer_id']?>&model_id=<?php echo $_GET['model_id']?>&engineId=<?php echo $_SESSION['engine_id']?>"><?php echo $_SESSION['model_series'][$_GET['model_id']]; ?></a> <br/></div>
			<div style="float: left;">
				&nbsp;>>&nbsp;
				<?php
					$count = 0;
					$exp = explode(' ', $_SESSION['label']);

					if($exp[0] == $_SESSION['manufacturers'][$_GET['manufacturer_id']])
						$count ++;
					$exp_models = explode(' ', $_SESSION['model_series'][$_GET['model_id']]);
					$count += count($exp_models);
					if($exp[$count] == end($exp_models))
						$count ++;
					$count_label = count ($exp);
					if($count < $count_label)
					{
						for($i = $count; $i <= $count_label; $i++)
						{
							$labelName = $labelName.' '.$exp[$i];
						}
					}
					else
					  $labelName = $_SESSION['label'];

					echo $labelName;
?>
			</div>
		</div>
	</div>
	<div style="clear: both;"></div>

	<div id="leftCategory">
		<div style="float: left; margin: 3px; border: 1px solid #dedede;">
			<a href="product_groups.php?id=<?php echo $_GET['id'];?>&manufacturer_id=<?php echo $_GET['manufacturer_id']; ?>&model_id=<?php echo $_GET['model_id']; ?>" title="<?php echo mb_convert_encoding('HOME','Windows-1251','UTF-8'); ?>">
				<img src="images/1.gif" alt="<?php echo $iconName[$data->nodeId]; ?>" />
			</a>
		</div>
		<div style="float: left; margin-left: 20px;">
			<div style="float: left; font-size: 14px; font-weight: bold;">
				<?php echo mb_convert_encoding('Ключова дума','Windows-1251','UTF-8'); ?>
			</div><br/>
			<form action = "<?php echo $_SERVER['PHP_SELF'].'?id='.$_GET['id'].'&manufacturer_id='.$_GET['manufacturer_id'].'&model_id='.$_GET['model_id']?>" method="post">
				<input type="text" name="filterText" class="input" maxlength="200" value="<?php echo $post; ?>"/>
				<input type="submit" class="btn" value="<?php echo mb_convert_encoding('Търси','Windows-1251','UTF-8'); ?>" />
			</form>
		</div>
	</div>
	<div style="clear: both;"></div>

	<div id="mainContent">
<?php
	if(empty($message))
	{
		// Check is result
		$flag = 0;
		$flag_show_product_manufacturer = false;
		foreach($results_products->tree as $key => $data)
		{
			if( (!empty($_GET['id'])) && (!empty($data->nodeId)) && (!empty($data->label)) )
			{
				$flag = 1;
?>
				<div id="<?php echo $data->nodeId;?>">
					<a href="<?php echo $_SERVER['PHP_SELF'];?>?id=<?php echo $_GET['id'];?>&sub_id=<?php echo $data->route;?>&manufacturer_id=<?php echo $_GET['manufacturer_id']; ?>&model_id=<?php echo $_GET['model_id'].$icon; ?>">
<?php
						if($data->leafNode == 0)
						{
							if( (!isset($_SESSION['flag_tree'][$_GET['id']][$data->nodeId])))
								echo '<b><img src="images/plus.gif" alt="+" /> '.$data->label.'</b>';
							elseif($_SESSION['flag_tree'][$_GET['id']][$data->nodeId] == true)
								echo '<b><img src="images/minus.gif" alt="-" /> '.$data->label.'</b>';
							else
								echo '<b><img src="images/plus.gif" alt="+" /> '.$data->label.'</b>';
						}
						else
							echo '<div style="float: left; margin-left: 3px; width: 9px; height: 9px;">
								<img src="images/dot.gif" alt="." /></div>'.$data->label;
?>
					</a>
				</div>
<?php
				if( ((isset($data->subnodes)) || (isset($_SESSION['tree'][$_GET['id']][$data->nodeId]))) && ( (!isset($_SESSION['flag_tree'][$_GET['id']][$data->nodeId])) || (isset($_SESSION['flag_tree'][$_GET['id']][$data->nodeId]) && $_SESSION['flag_tree'][$_GET['id']][$data->nodeId] == true))  ) //sublevel 1
				{
?>
					<div id="group_<?php echo $data->nodeId ?>" style="margin-left:15px;">
<?php
					if((!is_array($data->subnodes)) && isset($data->subnodes))
						$data->subnodes = array_filter(array($data->subnodes));
					if(isset($data->subnodes) && !empty($data->subnodes))
					{
						$_SESSION['flag_tree'][$_GET['id']][$data->nodeId] = true;
						$_SESSION['tree'][$_GET['id']][$data->nodeId] = $data->subnodes;
					}
					
					foreach($_SESSION['tree'][$_GET['id']][$data->nodeId] as $sub_level1)
					{
						if( ($last_sub_id == $sub_level1->nodeId) && ($sub_level1->leafNode != 0) )
							$flag_show_product_manufacturer = true;
?>
						<div id="<?php echo $sub_level1->nodeId;?>">
							<a href="<?php echo $_SERVER['PHP_SELF'];?>?id=<?php echo $_GET['id'];?>&sub_id=<?php echo implode('-', $sub_level1->route);?>&manufacturer_id=<?php echo $_GET['manufacturer_id']; ?>&model_id=<?php echo $_GET['model_id'].$icon; ?>">
<?php
								if($sub_level1->leafNode == 0)
								{
									if( (!isset($_SESSION['flag_tree'][$_GET['id']][$sub_level1->nodeId])))
										echo '<b><img src="images/plus.gif" alt="+" /> '.$sub_level1->label.'</b>';
									elseif($_SESSION['flag_tree'][$_GET['id']][$sub_level1->nodeId] == true)
										echo '<b><img src="images/minus.gif" alt="-" /> '.$sub_level1->label.'</b>';
									else
										echo '<b><img src="images/plus.gif" alt="+" /> '.$sub_level1->label.'</b>';
								}
								else
									echo '<div style="float: left; margin-left: 3px; width: 9px; height: 9px;">
									<img src="images/dot.gif" alt="." /></div>'.$sub_level1->label;
?>
							</a>
						</div>
<?php
						if( ((isset($sub_level1->subnodes)) || (isset($_SESSION['tree'][$_GET['id']][$sub_level1->nodeId]))) && ( (!isset($_SESSION['flag_tree'][$_GET['id']][$sub_level1->nodeId])) || (isset($_SESSION['flag_tree'][$_GET['id']][$sub_level1->nodeId]) && $_SESSION['flag_tree'][$_GET['id']][$sub_level1->nodeId] == true)) ) //sublevel 2
						{
?>
							<div id="group_<?php echo $sub_level1->nodeId ?>" style="margin-left:30px;">
<?php
							if(!is_array($sub_level1->subnodes) && isset($sub_level1->subnodes))
							$sub_level1->subnodes = array_filter(array($sub_level1->subnodes));
							
							if(isset($sub_level1->subnodes) && !empty($sub_level1->subnodes))
							{
								$_SESSION['flag_tree'][$_GET['id']][$sub_level1->nodeId] = true;
								$_SESSION['tree'][$_GET['id']][$sub_level1->nodeId] = $sub_level1->subnodes;
							}
							foreach($_SESSION['tree'][$_GET['id']][$sub_level1->nodeId] as $sub_level2)
							{
								if($last_sub_id == $sub_level2->nodeId)
									$flag_show_product_manufacturer = true;
?>
								<div id="<?php echo $sub_level2->nodeId;?>">
									<a href="<?php echo $_SERVER['PHP_SELF'];?>?id=<?php echo $_GET['id'];?>&sub_id=<?php echo implode('-', $sub_level2->route);?>&manufacturer_id=<?php echo $_GET['manufacturer_id']; ?>&model_id=<?php echo $_GET['model_id'].$icon; ?>">
<?php
										echo '<div style="float: left; margin-left: 3px; width: 9px; height: 9px;">
											<img src="images/dot.gif" alt="." /></div>'.$sub_level2->label;
?>
									</a>
								</div>
<?php
							}
?>
							</div>
<?php
						}
					}
?>
					</div>
<?php
				}
			}
		}
		
		if(empty($flag)){
?>
			<div class="no_result"><?php echo mb_convert_encoding('Няма намерени резултати','Windows-1251','UTF-8'); ?></div>
<?php
		}
	}
	else{
?>
		    <div style="margin-top: 5px; font-size: 12px; color: #ff0000; text-align: center;"><?php echo $message; ?></div>
<?php
		}
?>
	</div>

	<div id="product_manufacturer">
<?php
		if(isset($_GET['id']) && $_GET['id'] && $flag_show_product_manufacturer)
		{
			// Нашите доставчици от БД
			$query = sprintf("SELECT `provider_id`, `name` FROM `providers` WHERE `deleted` = 0");
			$results = mysql_query($query) or die(mysql_error());
			$num_rows = mysql_num_rows($results);

			$arrProviderTableMy = array();
			if($num_rows){
					while($fetch = mysql_fetch_assoc($results)){
						$arrProviderTableMy[$fetch['provider_id']] = mb_convert_encoding($fetch['name'],'Windows-1251','UTF-8');
				}
			}

			$parameters_articles = array('languageId'=>32,'treeType'=>1,'vehicleTypeId'=>$_GET['id'],'nodeId'=>$last_sub_id,'own'=>0);
			$result_article = $client->getArticleGroupsDealersForNode($parameters_articles);
			if(!is_array($result_article->articleGroupsDealers))
				$result_article->articleGroupsDealers = array('0' => $result_article->articleGroupsDealers);

			$array_other_providers = array();
			$flag_our_providers = 0;

			$_SESSION['dealer_ids'] = array();
			foreach($result_article->articleGroupsDealers as $dealer)
			{
				if( isset($dealer->dealerId) )
				{
					$_SESSION['dealer_ids'][] = $dealer->dealerId;
					if(!isset($client_articleGroupsDealers))
					{
						$options = array('languageId'=>$languageId,'trace' => 1,'login' => 'autohit2','password' => 'bont39er','encoding' => 'ISO-8859-1','trace' => true,'exceptions' => true);
						$client_articleGroupsDealers = new SoapClient('http://autohit.web-catalogue.eu/main/service/article.wsdl',$options);
					}
					// Всички доставчици с които работи autohit при извеждането на резултатите
					if(in_array($dealer->dealerName, $arrProviderTableMy))
					{
						$flag_our_providers = 1;
						$parameters_articleGroupsDealers = array(
							'languageId' => $languageId,
							'own' => 0,
							'vehicleTypeId' => 0+$_GET['id'],
							'genartIdTecDoc' => array(0+$dealer->articleGroupId),
							'dealerIdTecDoc' => array(0+$dealer->dealerId)
						);
						$result_articleGroupsDealers = $client_articleGroupsDealers->searchArticleByArticleGroup($parameters_articleGroupsDealers);
						$results_articleGroupsDealers[$dealer->articleGroupId.'_'. $dealer->dealerId] = $result_articleGroupsDealers;
						if( (isset($result_articleGroupsDealers->article)) )
						{
?>
							<div style="font-size:14px;">
								<a onClick="ajaxLoadHistory(<?php echo $_GET['manufacturer_id']; ?>,<?php echo $_GET['model_id']; ?>,<?php echo $_GET['id']; ?>);" href="result.php?id=<?php echo $dealer->articleGroupId.'&dealer_id='. $dealer->dealerId;?>&manufacturer_id=<?php echo $_GET['manufacturer_id']; ?>&model_id=<?php echo $_GET['model_id']; ?>&product_id=<?php echo $_GET['id']; ?>" target="_blank" style="font-weight:bold;"><?php echo $dealer->dealerName;?></a>
								<a href="results.php?id=<?php echo $dealer->articleGroupId?>&manufacturer_id=<?php echo $_GET['manufacturer_id']; ?>&model_id=<?php echo $_GET['model_id']; ?>&product_id=<?php echo $_GET['id']?>" target="_blank" style="font-size:12px;float:right;"><?php echo $dealer->articleGroupName; ?></a>
							</div>
<?php
						}
					}
					else
						$array_other_providers[] = $dealer;
				}
			}

			if( ($flag_our_providers === 0) || ($flag_our_providers && isset($_GET['allproviders'])) )
			{
				if(!isset($client_articleGroupsDealers))
				{
					$options = array('languageId'=>$languageId,'trace' => 1,'login' => 'autohit2','password' => 'bont39er','encoding' => 'ISO-8859-1','trace' => true,'exceptions' => true);
					$client_articleGroupsDealers = new SoapClient('http://autohit.web-catalogue.eu/main/service/article.wsdl',$options);
				}

				foreach($array_other_providers as $dealer)
				{
					$parameters_articleGroupsDealers = array(
						'languageId' => $languageId,
						'own' => 0,
						'vehicleTypeId' => 0+$_GET['id'],
						'genartIdTecDoc' => array(0+$dealer->articleGroupId),
						'dealerIdTecDoc' => array(0+$dealer->dealerId),
					);
					$result_articleGroupsDealers = $client_articleGroupsDealers->searchArticleByArticleGroup($parameters_articleGroupsDealers);
					$results_articleGroupsDealers[$dealer->articleGroupId.'_'. $dealer->dealerId] = $result_articleGroupsDealers;
					if( (isset($result_articleGroupsDealers->article)) )
					{
?>
						<div style="font-size:13px; margin: 2px 0;">
							<a href="result.php?id=<?php echo $dealer->articleGroupId.'&dealer_id='. $dealer->dealerId;?>&manufacturer_id=<?php echo $_GET['manufacturer_id']; ?>&model_id=<?php echo $_GET['model_id']; ?>&product_id=<?php echo $_GET['id']; ?>" target="_blank"><?php echo $dealer->dealerName;?></a>
							<a href="results.php?id=<?php echo $dealer->articleGroupId?>&manufacturer_id=<?php echo $_GET['manufacturer_id']; ?>&model_id=<?php echo $_GET['model_id']; ?>&product_id=<?php echo $_GET['id']?>" target="_blank" style="font-size:12px;float:right;"><?php echo $dealer->articleGroupName; ?></a>
						</div>
<?php
					}
				}
			}
			elseif(!empty($array_other_providers))
			{
?>
				<div style="float: left; margin-top: 10px; width: 100%;">
					<img src="images/arrow_right.png" alt="" style="float: left; margin-right: 7px;" />
					<a href="<?php echo $_SERVER['PHP_SELF'];?>?id=<?php echo $_GET['id'];?>&sub_id=<?php echo $_GET['sub_id'];?>&manufacturer_id=<?php echo $_GET['manufacturer_id']; ?>&model_id=<?php echo $_GET['model_id'].$icon.'&allproviders=1' ?>" style="float: left; font-size: 13px; text-decoration: underline;"><b><?php echo mb_convert_encoding('Всички доставчици','Windows-1251','UTF-8'); ?></b></span>
				</div>
<?php
			}
		}
?>
	</div>
	<div style = "clear:both;"></div>

<?php
	if(isset($results_articleGroupsDealers)){
		$_SESSION['articleGroupsDealers'] = $results_articleGroupsDealers;
	}
}
?>
</body>
</html>